<?php
declare (strict_types=1);

namespace app\controller;

use app\handler\Aes;
use app\handler\JwtAuth;
use app\helpers\api\ApiResponse;
use app\model\Company;
use app\model\User;
use think\Request;

class TokenController
{
    use ApiResponse;

    public function store(Aes $aes, Request $request)
    {
        $user = User::where('name|email', $request->param('name'))
            ->where('password', $aes->encode($request->param('password')))
            ->findOrEmpty();
        if (!$user->isEmpty()) {
            $jwtAuth = JwtAuth::getInstance();
            $token   = $jwtAuth->setUid($user->id . ',' . $user->type)->encode()->getToken();
            unset($user['password']);
            return $this->success([
                'token'=>$token,
                'user'=>$user
            ]);
        } else {
            return $this->failed('用户名或密码错误');
        }
    }

    public function companyStore(Aes $aes, Request $request)
    {
        $company = Company::where('name|email', $request->param('name'))
            ->where('password', $aes->encode($request->param('password')))
            ->findOrEmpty();
        if (!$company->isEmpty()) {
            if($company->state != 1) return $this->failed('企业审核未通过');
            $jwtAuth = JwtAuth::getInstance();
            $token   = $jwtAuth->setUid($company->id . ',' . $company->state)->encode()->getToken();
            return $this->success([
                'token'=>$token,
                'user'=>$company
            ]);
        } else {
            return $this->failed('用户名或密码错误');
        }
    }
}
